using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

using Walkmen.Util;

namespace Walkmen.ID3v2
{
    public class ID3v2Header
    {
        private string _fileType;
        private short _version;
        private byte _flag;
        private int _size;
        private readonly ID3v2FrameCollection _frames = new ID3v2FrameCollection();

        public ID3v2FrameCollection Frames
        {
            get { return _frames; }
        }

        public string FileType
        {
            get { return _fileType; }
            set { _fileType = value; }
        }

        public short Version
        {
            get { return _version; }
            set { _version = value; }
        }

        public byte Flag
        {
            get { return _flag; }
            set { _flag = value; }
        }

        public int Size
        {
            get { return _size; }
            set { _size = value; }
        }

        public byte[] ToArray()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                byte[] fileType = Encoding.ASCII.GetBytes(_fileType);
                stream.Write(fileType, 0, fileType.Length);

                byte[] version = NumericUtils.WriteShort(_version);
                stream.Write(version, 0, version.Length);

                stream.WriteByte(_flag);

                byte[] frames = null;
                using (MemoryStream buffer = new MemoryStream())
                {
                    foreach (ID3v2Frame frame in _frames)
                    {
                        byte[] data = frame.ToArray();
                        buffer.Write(data, 0, data.Length);
                    }
                    frames = buffer.ToArray();
                }

                byte[] size = NumericUtils.WriteSynchsafeInt32((int)frames.Length);
                stream.Write(size, 0, size.Length);

                stream.Write(frames, 0, frames.Length);

                return stream.ToArray();
            }
        }
    }
}
